package com.anda.softtest.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;

import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EncodingUtils;

import android.content.Context;

import com.anda.softtest.R;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonCodeUtil {
	private static JsonCode jsonCode;
	private static JsonCodeUtil jsonCodeUtil = null;
	private Context context;
	private JsonCodeUtil(Context context){
		this.context = context;
		getObjectFromJson();
	}
	public static JsonCodeUtil getInstance(Context context){
		if ( jsonCodeUtil == null ) {
			jsonCodeUtil = new JsonCodeUtil(context);
		}
		return jsonCodeUtil;
	}
	
	public String getCodeText(String codeName, String codeValue){
		if (jsonCode.getStatus().equals("OK") && jsonCode.getData().containsKey(codeName)){
			if (jsonCode.getData().get(codeName).containsKey(codeValue)){
				return jsonCode.getData().get(codeName).get(codeValue);
			}
		}
		return "";
	}
	private void getObjectFromJson(){
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			String json = readJsonRegion();
			jsonCode = objectMapper.readValue(json, JsonCode.class);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	private String readJsonRegion(){
		InputStream is = context.getResources().openRawResource(R.raw.jsoncode); 
		ByteArrayBuffer bb = new ByteArrayBuffer(1024);
		int current=0;
		try {
			while((current = is.read())!=-1)
			{
				bb.append(current);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return EncodingUtils.getString(bb.toByteArray(),"GBK");
	}
	
	static class JsonCode {
		String status;
		LinkedHashMap<String, LinkedHashMap<String, String>> data;
		public String getStatus() {
			return status;
		}
		public void setStatus(String status) {
			this.status = status;
		}
		public LinkedHashMap<String, LinkedHashMap<String, String>> getData() {
			return data;
		}
		public void setData(LinkedHashMap<String, LinkedHashMap<String, String>> data) {
			this.data = data;
		}
		
	}
}
